package org.mm.ec.search.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.highlight.HighlightField;
import org.mm.ec.search.store.Vedios;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

@Service
public class SearchVediosService {
	@Autowired
	private Client esClient;

	/**
	 * 批量创建索引
	 */
	public void createSearchIndex(List<Vedios> listVedio) {
		BulkRequestBuilder bulkRequest = esClient.prepareBulk();
		for (Vedios vedios : listVedio) {
			bulkRequest
					.add(esClient
							.prepareIndex("watone", "vedios",
									vedios.getId().toString())
							.setSource(JSON.toJSONString(vedios)).request());
		}

		BulkResponse response = bulkRequest.execute().actionGet();
	}

	/**
	 * 批量创建索引
	 */
	public void createSearchIndex(Vedios v) {
		IndexResponse response = esClient
				.prepareIndex("watone", "vedios", v.getId().toString())
				.setSource(JSON.toJSONString(v)).execute().actionGet();
	}

	/**
	 * 模糊搜索
	 * 
	 * @param param
	 * @return
	 */
	public List<Vedios> searchs(String param, int from, int size) {
		SearchResponse response = esClient.prepareSearch("watone")
				.setTypes("vedios")
				.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
				.setQuery(QueryBuilders.queryString(param)).setFrom(from)
				.setSize(size).setExplain(true).addHighlightedField("desc")
				.setHighlighterPreTags("<span style=\"color:red\">")
				.setHighlighterPostTags("</span>").execute().actionGet();
		SearchHits hits = response.getHits();
		List<Vedios> list = new ArrayList<Vedios>();
		for (int i = 0; i < hits.getHits().length; i++) {
			Vedios v = new Vedios();
			if (hits.getAt(i).getSource().get("id") != null) {
				v.setId(Integer.parseInt(hits.getAt(i).getSource().get("id")
						.toString()));
			}
			if (hits.getAt(i).getSource().get("vedioNo") != null) {
				v.setVedioNo(hits.getAt(i).getSource().get("vedioNo")
						.toString());
			}
			if (hits.getAt(i).getSource().get("name") != null) {
				v.setName(hits.getAt(i).getSource().get("name").toString());
			}
			if (hits.getAt(i).getSource().get("desc") != null) {
				Map<String, HighlightField> result = hits.getAt(i)
						.highlightFields();
				// 从设定的高亮域中取得指定域
				HighlightField titleField = result.get("desc");
				// 取得定义的高亮标签
				if (titleField != null) {
					Text[] titleTexts = titleField.fragments();
					// 为title串值增加自定义的高亮标签
					String desc = "";
					for (Text text : titleTexts) {
						desc += text;
					}
					v.setDesc(desc);
				} else
					v.setDesc("");

			}
			if (hits.getAt(i).getSource().get("title") != null) {
				v.setTitle(hits.getAt(i).getSource().get("title").toString());
			}
			if (hits.getAt(i).getSource().get("vedioThumb") != null) {
				v.setVedioThumb(hits.getAt(i).getSource().get("vedioThumb")
						.toString());
			}
			list.add(v);
		}
		return list;
	}

	/**
	 * 删除索引，通过id删除
	 * 
	 * @param id
	 * @return
	 */
	public int deleteIndex(Integer id) {
		DeleteResponse dr = null;
		dr = esClient.prepareDelete("watone", "vedios", id.toString())
				.execute().actionGet();
		return 1;
	}

	/**
	 * 批量刪除索引
	 * 
	 * @return
	 */
	public int deleteIndex(List<Vedios> listVedio) {
		BulkRequestBuilder deleteBulk = esClient.prepareBulk();
		for (Vedios vedios : listVedio) {
			deleteBulk
					.add(esClient
							.prepareIndex("watone", "vedios",
									vedios.getId().toString())
							.setSource(JSON.toJSONString(vedios)).request());
		}
		deleteBulk.execute().actionGet();
		return 1;
	}
}
